package com.sanerzone.smscenter.modules.sms.task;

import com.sanerzone.jeebase.common.persistence.Page;
import com.sanerzone.jeebase.common.utils.DateUtils;
import com.sanerzone.jeebase.common.utils.SpringContextHolder;
import com.sanerzone.smscenter.modules.sms.entity.SmsSend;
import com.sanerzone.smscenter.modules.sms.service.SmsSendService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

//定时任务 短信日报表、任务统计
@Service
@Lazy(false)
public class
SmsSendDayPutMonthTask {
	
	public static Logger logger = LoggerFactory.getLogger(SmsSendDayPutMonthTask.class);

	@Autowired
	private  SmsSendService smsSendService;

	private static final int BATCH_COMMIT_MAX_COUNT = 1000;//批量提交默认值;


//	@Scheduled(cron = "0 0/1 * * * ?")
	@Scheduled(cron = "0 15 2 * * ?")
	public void exec(){
		SmsSend smsSend = new SmsSend();
		String tableName = "sms_send_"+DateUtils.getDayOfMonth(-4);
		logger.info("短信日表转移到月表定时任务，数据库表：{}", tableName);
		smsSend.setTableName(tableName);
		Page<SmsSend> page = new Page<SmsSend>(1, BATCH_COMMIT_MAX_COUNT);
		page = smsSendService.findPage(page, smsSend);
		List<SmsSend> list = page.getList();
		while (list != null && list.size() > 0) {
			SqlSession sqlSession = SpringContextHolder.getBean(SqlSessionFactory.class).openSession(ExecutorType.BATCH, false);
			int insertCount = 0;
			try{
				for (SmsSend smsSendDay :list){
					insertCount++;
					Date date = DateUtils.getDay( -4 );
					String month = DateUtils.formatDate( date, "MM" );
					String yy = DateUtils.formatDate( date, "yyyy" );
					smsSendDay.setTableName( "sms_send_history_" + yy + month );
					sqlSession.insert( "com.sanerzone.smscenter.modules.sms.dao.SmsSendDao.insert", smsSendDay );//批量提交

					smsSendDay.setTableName( "sms_send_" + DateUtils.getDayOfMonth( -4 ) );
					sqlSession.delete( "com.sanerzone.smscenter.modules.sms.dao.SmsSendDao.delete", smsSendDay );//批量提交

					if(insertCount % BATCH_COMMIT_MAX_COUNT == 0){
						sqlSession.commit();
					}
				}
				sqlSession.commit();
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("SmsSend day put month batch error:{}",e);
			} finally {
				sqlSession.close();
			}
			page = smsSendService.findPage(page, smsSend);
			list = page.getList();
		}
	}
}
